package com.itheima.reggie.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.Common.BaseContext;
import com.itheima.reggie.Mapper.ShoppingCartMapper;
import com.itheima.reggie.Service.ShoppingCartService;
import com.itheima.reggie.entity.ShoppingCart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {


    @Autowired
    private ShoppingCartService shoppingCartService;
    /**
     * 购物车的修改功能
     * @param shoppingCart
     * @return
     */
    @Override
    public ShoppingCart sub(ShoppingCart shoppingCart) {
        //获取用户的id
        Long userId = BaseContext.getCurrentId();

        //获取菜品的id
        Long dishId = shoppingCart.getDishId();

        ShoppingCart shoppingCart1 = null;
        //条件构造器
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper();
        //指定是哪个用户的购物车

        if(dishId!=null){
            //修改的是菜品的数量，同草品和套餐数量的=增加
            queryWrapper.eq(ShoppingCart::getDishId,dishId);
            shoppingCart1 = this.getOne(queryWrapper);
        }else{
            //修改的是套餐的数量
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
            shoppingCart1 = this.getOne(queryWrapper);
        }

        //如果购物车中的数量大于一份，则其相应的套餐数量减一
        shoppingCart1.setNumber(shoppingCart1.getNumber()-1);
        if(shoppingCart1.getNumber()>0){
            //如果还有套餐更新数据
            this.updateById(shoppingCart1);
        }else {
            //如果菜品或者套餐数量为0就删除
            this.removeById(shoppingCart1);
        }

        return shoppingCart1;
    }

    @Override
    public void clean() {

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        shoppingCartService.remove(queryWrapper);
    }
}
